package com.ambulance.project.websockt;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;


/**
 * @author
 */
@ServerEndpoint("/imserver/{identity}")
@Component
public class WebSocketServer {

    private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象0。
     */
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。必须要有的
    private static CopyOnWriteArraySet<WebSocketServer>
            webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收identity
     */
    private String identity = "";

    /**
     * 发送自定义消息
     */
    public void sendInfo(String message, @PathParam("identity") String identity) throws IOException {

        if (StringUtils.isNotBlank(identity) && webSocketMap.containsKey(identity)) {
            webSocketMap.get(identity).sendMessage(message);
        } else {
            WebSocketUtils.sendMessageAll(message);
            log.error("用户{}不在线！", identity);
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("identity") String identity) throws IOException {
        this.session = session;
        this.identity = identity;
        if (webSocketMap.containsKey(identity)) {
            webSocketMap.remove(identity);
            webSocketMap.put(identity, this);
//            sendMessage("该连接已存在");
            sendInfo("该Socket连接正被重复连接",identity);
            addOnlineCount();
            //加入set中
        } else {
            webSocketMap.put(identity, this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }
        if(identity.equals("sign")){
            webSocketSet.add(this);     //加入set中
//            addOnlineCount();
        }
        System.out.println("------------------------------------");
        System.out.println(webSocketSet);
        log.info("用户连接:" + identity + ",当前在线人数为:" + getOnlineCount());
        try {
            //连接连接后发送数据
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("用户:" + identity + ",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(identity)) {
            webSocketMap.remove(identity);
            //从set中删除
        }
        subOnlineCount();
        webSocketSet.remove(this);  //从set中删除
        System.out.println(webSocketSet);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:" + identity + ",报文:" + message);
        //可以群发消息
        //消息保存到数据库、redis
        if (StringUtils.isNotBlank(message)) {
            try {
                //todo 解析发送的报文
                System.out.println(message);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生错误的时候触发
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.identity + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public  void send2AllInfo(String message) throws IOException {
        System.out.println("推送消息内容:" + message);
//        Enumeration<String> keys = webSocketMap.keys();
        ConcurrentHashMap.KeySetView<String, WebSocketServer> keySet = webSocketMap.keySet();
        for ( String entry:keySet){
            WebSocketServer webSocketServer = webSocketMap.get(entry);
            webSocketServer.sendMessage(message);
        }
    }
    /**
     * 群发自定义消息
     */
    public  void sendInfo(String message){
        System.out.println("推送消息内容:" + message);
        System.out.println("----------------------------");
        System.out.println(webSocketSet);
        for (WebSocketServer item : webSocketSet) {
            try {
                System.out.println(item);
                System.out.println("-------");
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }
}
